<?php
namespace app\service;

class Pl5 {
    public function getLast(){
        $res = $this->getPl5(1, 1);
        if (!$res['status']) {
            return $res;
        }
        $installAll = $this->formatData($res['data']['value']['list']);
        $model = new \app\model\Pl5;
        try{
            $model->insert($installAll[0]);
        }catch(\Exception $e){
            return [
                'status' => false, 
                'code' => 25052801, 
                'msg' => $e->getMessage(), 
                'param' => [
                    'pageNo' => 1, 
                    'pageSize' => 1
                ],
                'sql' => $model->getLastSql()
            ];
        }
        return ['status' => true];
    }
    public function getAll($pages = 243){
        for ($i = 1; $i <= $pages; $i++) {
            $res = $this->getPl5($i, 30);
            if (!$res['status']) {
                return $res;
            }
            $installAll = $this->formatData($res['data']['value']['list']);
            $model = new \app\model\Pl5;
            try{
                $model->insertAll($installAll);
            }catch(\Exception $e){
                return [
                    'status' => false, 
                    'code' => 25052802, 
                    'msg' => $e->getMessage(), 
                    'param' => [
                        'pageNo' => $i, 
                        'pageSize' => 30
                    ]
                ];
            }
        }
        return ['status' => true];
    }

    public function getPl5($pageNo = 1, $pageSize = 30){
        $url = "https://webapi.sporttery.cn/gateway/lottery/getHistoryPageListV1.qry";
        $params = [
            'gameNo' => '350133',
            'provinceId' => '0',
            'pageSize' => $pageSize,
            'isVerify' => '1',
            'pageNo' => $pageNo
        ];
        
        $url .= '?' . http_build_query($params);
        
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'accept: application/json, text/javascript, */*; q=0.01',
            'accept-language: zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
            'origin: https://static.sporttery.cn',
            'referer: https://static.sporttery.cn/',
            'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0',
            'x-dev-fp: 3d2905c953c2feadb619cf9bfa3114c6',
            'x-full-ref: //www.lottery.gov.cn/kj/kjlb.html?plw'
        ]);
        
        $response = curl_exec($ch);

        if (curl_errno($ch)){
            $error = curl_error($ch);
            curl_close($ch);
            return [
                'status' => false,
                'code' => 25052803, 
                'msg' => $error, 
                'html' => $response, 
                'param' => [
                    'pageNo' => $pageNo, 
                    'pageSize' => $pageSize
                ]
            ];
        }

        curl_close($ch);

        $result = json_decode($response, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            return [
                'status' => false, 
                'code' => 25052804, 
                'msg' => json_last_error_msg(), 
                'html' => $response, 
                'param' => [
                    'pageNo' => $pageNo, 
                    'pageSize' => $pageSize
                ]
            ];
        }

        if (!$result['success']) {
            return [
                'status' => false, 
                'code' => 25052805, 
                'msg' => $result['errorMessage'],
                'data' => $result,
                'param' => [
                    'pageNo' => $pageNo, 
                    'pageSize' => $pageSize
                ]
            ];
        }
        if (empty($result['value']['list'])) {
            return [
                'status' => false,
                'code' => 25052806,
                'msg' => '没有数据',
                'data' => $result,
                'param' => [
                    'pageNo' => $pageNo, 
                    'pageSize' => $pageSize
                ]
            ];
        }
        
        return [
            'status' => true,
            'data' => $result,
            'param' => [
                'pageNo' => $pageNo, 
                'pageSize' => $pageSize
            ]
        ];
    }

    /**
     * 格式化数据
     * @param array $list API返回的数据列表
     * @return array 格式化后的数据列表
     */
    private function formatData($list)
    {
        $transformedList = [];
        foreach ($list as $item) {
            // 拆分开奖结果
            $numbers = explode(' ', $item['lotteryDrawResult']);
            
            $transformedList[] = [
                'lottery_draw_num' => $item['lotteryDrawNum'],
                'lottery_game_name' => $item['lotteryGameName'],
                'lottery_game_num' => $item['lotteryGameNum'],
                'lottery_draw_result' => $item['lotteryDrawResult'],
                'num1' => $numbers[0],
                'num2' => $numbers[1],
                'num3' => $numbers[2],
                'num4' => $numbers[3],
                'num5' => $numbers[4],
                'lottery_draw_time' => $item['lotteryDrawTime'],
                'lottery_draw_status' => $item['lotteryDrawStatus'],
                'total_sale_amount' => floatval(str_replace(',', '', $item['totalSaleAmount'])),
                'pool_balance_afterdraw' => floatval(str_replace(',', '', $item['poolBalanceAfterdraw'])),
                'draw_flow_fund' => floatval(str_replace(',', '', $item['drawFlowFund'])),
                'lottery_paid_begin_time' => $item['lotteryPaidBeginTime']?:'0000-00-00 00:00:00',
                'lottery_paid_end_time' => $item['lotteryPaidEndTime']?:'0000-00-00 00:00:00',
                'lottery_sale_begin_time' => $item['lotterySaleBeginTime'],
                'lottery_sale_end_time' => $item['lotterySaleEndtime'],
                'draw_pdf_url' => $item['drawPdfUrl'],
                'verify' => $item['verify'],
                'stake_count' => !empty($item['prizeLevelList']) ? intval($item['prizeLevelList'][0]['stakeCount']) : 0,
                'total_prize_amount' => !empty($item['prizeLevelList']) ? floatval(str_replace(',', '', $item['prizeLevelList'][0]['totalPrizeamount'])) : 0
            ];
        }
        
        return $transformedList;
    }
}